#include<iostream>
#include <cstring>
#include <ctime>
#include <unistd.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "lockguard.hpp"
#include "Socket.hpp"
#include "Protocol.hpp"


int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server-ip server-port" << std::endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    SockSPtr sock = std::make_shared<TcpSocket>();
    if(!sock->BuildClientSocket(serverip,serverport))
    {
    LOG(DEBUG,"client 111\n");
	    exit(9);
    }
    srand(time(nullptr));
    const std::string opers="+-*/%!#^&";
    std::string packagestream;
    while(true)
    {
	    sleep(1);
	int x =rand()%10;
	usleep(x * 100);
	int y =rand()%10;
	usleep(x * y * 10);
        char oper = opers[y % opers.size()];
	shared_ptr<Request> req =make_shared<Request>(x,y,oper);
	req->Print();
	//1.序列化
	string jsonreq;
	req->Serialize(&jsonreq);
	//2.添加报头
	jsonreq=Encode(jsonreq);
	//3.发送
	sock->Send(jsonreq);
	while(1)
	{
	//4.接受
	int n=sock->Recv(&packagestream);
	if(n<0) break;
	//5.解析报头
	std::string package = Decode(packagestream);
	if(package.size()==0)
		continue;
	//6.反序列化
	shared_ptr<Response> res=make_shared<Response>();
	res->Deserialize(package);
	//7.打印结果
	res->Print();
	break;

	};

    };
    sock->Close();
	return 0;

};
